import { bindable, containerless } from 'aurelia-framework';

@containerless
export class EmTaskSearch {

    projects = [];

    types = [{
        id: 'Task',
        name: "任务",
    }, {
        id: 'Epic',
        name: "史诗",
    }, {
        id: 'Story',
        name: "故事",
    }, {
        id: 'Improvement',
        name: "改进",
    }, {
        id: 'Feature',
        name: "新功能",
    }, {
        id: 'Issue',
        name: "缺陷",
    }];

    states = [];

    operators = [];

    search = {
        projects: null,
        types: null,
        states: null,
        operators: null,
    };

    _triggerSearch() {
        ea.publish(nsCons.EVENT_TASK_SEARCH, this.search);
    }

    projectChangeHandler(projects) {
        this.search.projects = projects;
        this._triggerSearch();
        if (!projects || !projects.length) {
            projects = this.projects;
        }
        this._listByProjects(projects);
    }

    typeChangeHandler(types) {
        this.search.types = types;
        this._triggerSearch();
    }

    stateChangeHandler(states) {
        this.search.states = states;
        this._triggerSearch();
    }

    operatorChangeHandler(operators) {
        this.search.operators = operators;
        this._triggerSearch();
    }

    _listByProjects(projects) {
        this._listStatesByProjects(_.map(projects, "id"));
        this.joinMembersOfProjects(projects);
    }

    /**
     * 当数据绑定引擎绑定到视图时被调用
     * @param  {[object]} bindingCtx: The "binding context" to which the component is being bound will be passed first.
     * @param  {[object]} overrideCtx: The override context contains information used to traverse the parent hierarchy and can also be used to add any contextual properties that the component wants to add.
     */
    bind(bindingCtx, overrideCtx) {
        this._listMyProjects().then(() => {
            this._listByProjects(this.projects);
        });
    }

    joinMembersOfProjects(projects) {

        let members = _.unionBy(..._.map(projects, 'members'), 'username');
        this.operators = _.map(members, m => {
            return {
                id: m.username,
                name: m.name
            };
        })
    }

    _listStatesByProjects(pids) {
        return $.get(`/admin/task/status/listByProjects`, {
            pids: _.join(pids)
        }, data => {
            if (data.success) {
                this.states = data.data;
            } else {
                toastr.error(data.data);
            }
        });
    }

    _listMyProjects() {
        return $.get(`/admin/task/project/listMy`, {

        }, (data) => {
            if (data.success) {
                this.projects = data.data;
            } else {
                toastr.error(data.data);
            }
        });
    }

    /**
     * 当视图被附加到DOM中时被调用
     */
    attached() {

    }
}
